﻿using Microsoft.EntityFrameworkCore;

namespace _16一对多;

class Program
{
    static async Task Main(string[] args)
    {
        using MyContext ctx = new MyContext();
        // Article a1 = new Article() {Title = "testTitle",Content = "testContent"};
        // Comment c1 = new Comment() { Message = "test comment1"};
        // Comment c2 = new Comment() {Message = "test comment2"};
        // a1.Comments.AddRange([c1,c2]);
        // ctx.Articles.Add(a1);
        // Comment c3 = new Comment() { Message = "test3_1",Article = new Article(){Title = "testTitle3",Content = "testContent3"}};
        // ctx.Comments.Add(c3);
        // ctx.SaveChanges();
        /*
        Article a1 = ctx.Articles.Include(a => a.Comments).Single(a => a.ID == 1);
        Console.WriteLine(a1.Title+","+a1.Content);
        foreach (var comment in a1.Comments)
        {
            Console.WriteLine(comment.Message);
        }
        var c1 = ctx.Comments.Select(c=>new {c.ID,c.ArticleID}).Single(c => c.ID == 3);
        Console.WriteLine($"{c1.ID},{c1.ArticleID}");*/
        
        //查询所有评论里包含的指定内容所对应的文章的两种实现形式
        // var articles = await ctx.Articles.Where(a => a.Comments.Any(c=>c.Message.Contains("哇哦"))).ToListAsync();
        /*var articles = await ctx.Comments
            .Where(c => c.Message.Contains("哇哦"))
            .Select(c => c.Article).Distinct()
            .ToListAsync();
        foreach (var a in articles) 
        {
            Console.WriteLine(a.Title);
        }

        var res = ctx.Database.SqlQuery<int>($"123");
        var result = await ctx.Database.ExecuteSqlInterpolatedAsync($"123{123}");*/
        
        // var firstArticle = await ctx.Articles.AsNoTracking().FirstOrDefaultAsync();
        // Console.WriteLine($"{firstArticle.Title},{ctx.Entry(firstArticle).State}");

        // Article a1 = new Article() {ID=1, Title = "ChangeTitleTest" };
        // var e1 = ctx.Entry(a1);
        // e1.Property("Title").IsModified = true;
        // await ctx.SaveChangesAsync();

        var items = ctx.Articles.IgnoreQueryFilters().Take(3);
        foreach (var item in items)
        {
            Console.WriteLine($"{item.Title},{item.Content},{item.IsDeleted}");
        }
        // foreach (var item in items)
        // {
        //     item.IsDeleted = true;
        //     Console.WriteLine($"CurrentState:{ctx.Entry(item).State}");
        // }
        // await ctx.SaveChangesAsync();    
        
    }
    
}